home *** CD-ROM | disk | FTP | other *** search
Text File | 1998-06-19 | 2.4 KB | 116 lines | [TEXT/CWIE] |
- /*
- Problem 01 - Mode Sort
-
- This problem is to sort an input string of N characters, N<1000000, based on
- the number of times a character occurs in the input. The most frequently
- occurring character should be sorted to the front of the string, followed by
- the next most frequently occurring character, etc. For characters occurring
- the same number of times, the character that occurs first in the input should
- be sorted to the front.
-
- Header specification
-
- pascal OSErr ModeSort( const FSSpec* infile, const FSSpec* outfile );
-
- Input specification
-
- The infile input file contains the characters. Input characters other than
- those printable low ascii characters c, 0x20<c<0x7f, must be ignored.
-
- Output specification
-
- The outfile must be created and then filled with the sorted characters. It's
- final length should be exactly the same as the count of characters in the
- allowed range (0x20<c<0x7f) (which may be shorter than the infile file length).
-
- Sample input
-
- abcdefghabbcccdddeee
- or
- 012345678911234567892123456789312345678941234567895123456789612345678971234567891
-
- Sample output
-
- ccccddddeeeebbbaafgh
- or
- 111111111122222222233333333344444444455555555566666666677777777788888888999999990
- */
-
- #include "Solution.h"
-
- // Fill in your solution and then submit this folder
-
- // Team Name: Bob Hearn
-
- unsigned char *InputData;
-
- long Count[0x80];
- long First[0x80];
-
-
- pascal OSErr ModeSort( const FSSpec* infile, const FSSpec* outfile )
- {
- long size;
- short rn;
- unsigned char c;
- long x;
- long max;
- long maxfirst;
- unsigned char maxindex;
- long reqsize = 1;
- OSErr err;
-
- err = FSpOpenDF( infile, fsRdPerm, &rn );
- err = GetEOF(rn, &size);
-
- InputData = (unsigned char *) NewPtr(size);
- err = FSRead( rn, &size, InputData );
- err = FSClose( rn );
-
- for (c = 0x21; c < 0x80; ++c)
- {
- Count[c] = 0;
- First[c] = -1;
-
- for (x = 0; x < size; ++x)
- if (InputData[x] == c)
- {
- ++Count[c];
-
- if (First[c] == -1)
- First[c] = x;
- }
- }
-
- err = FSpCreate( outfile, 'CWIE', 'TEXT', 0 );
- err = FSpOpenDF( outfile, fsWrPerm, &rn );
- err = SetEOF(rn, 0);
-
- do
- {
- for (c = 0x21, max = 0; c < 0x80; ++c)
- {
- if (Count[c] > max || Count[c] == max && First[c] < maxfirst)
- {
- max = Count[c];
- maxindex = c;
- maxfirst = First[c];
- }
- }
-
- Count[maxindex] = 0;
-
- if (max)
- for (x = 0; x < max; ++x)
- {
- err = FSWrite( rn, &reqsize, &maxindex );
- x = x;
- }
-
- } while(max);
-
- FSClose(rn);
-
- return noErr;
- }
-